package disjunction.examples.basics
{
	import disjunction.core.*;
	import disjunction.core.geom.Vector2;
	
	import flash.geom.Point;

	/**
	 *
	 *
	 * @author Nick Wiggill
	 */
	
	public class DemoController extends Controller
	{
		public override function initialise(data:Object):void
		{
			//1. Prepare model.
			//Model is defined partly by Controller's own dicates, and partly
			//by incoming state initialisation data. Either-or is fine.
			model = {position: new Point(50, 50), motion: new Point(100, 50), radius: 7};
			model.worldDimensions = data.viewDimensions;
			
			//2. Prepare view.
			var view:DemoView = new DemoView();
			view.model = model; //must be done before initialisation
			view.initialise(data.viewContext);
			views["main"] = view;
			
			//3. Prepare and run controller updates.
			timer.baseUpdateIntervalMs = 20; //50 fps
			timer.updateTimeoutMs = 500;
			timer.start();
		}
		
		public override function update(timeDeltaMs:uint):void
		{
			//get view we wish to act on
			var view:DemoView = views["main"];
			
			//apply motion in pixels per second
			model.position.x += model.motion.x * timeDeltaMs/1000; 
			model.position.y += model.motion.y * timeDeltaMs/1000;
			
			//bounce if edge hit
			if (model.position.x < model.radius ||
				model.position.x > model.worldDimensions.x - model.radius)
				reverseMotionInX();
			
			if (model.position.y < model.radius ||
				model.position.y > model.worldDimensions.y - model.radius)
				reverseMotionInY();
			
			view.update(timeDeltaMs);
		}
		
		private function reverseMotionInX():void
		{
			model.motion.x *= -1;
		}
		private function reverseMotionInY():void
		{
			model.motion.y *= -1;
		}
	}
}